<template>
  <div class="container">
    <toast-layer v-if="toastShow" :toastContent="toastContent" :toastDesc="toastDesc" :toastType="toastType"></toast-layer>
    <div class="img-main pad-l-15 pad-r-15 pad-t-13">
      <!-- 详情图开始 -->
      <template v-if="mainNone">
        <div class="flex flex-between img-title">
          <span class="font-color-6 font-13 flex-item">分享图片</span>
          <button size="mini" class="mini-btn font-12" @click="downLoad">下载</button>
        </div>
        <div class="img-box">
          <div v-for="(item, index) in mainImgs" :key="index"
            class="img-bar" @click="checkClick(item, index)">
            <van-checkbox :value="item.checked" :checked-color="globalStyle.color2">
              <img v-if="item" class="width-99 height-99" mode="aspectFill" :src="item.src"/>
            </van-checkbox>
          </div>        
        </div>
        <p>下载速度根据您当前的实际网络速度而定，期间请勿操作耐心等待。</p>
      </template>
      <!-- 详情图结束 -->
    </div>
    <div class="copywriting pad-l-15 pad-r-15 mar-t-20">
      <div class="flex flex-between img-title">
        <span class="font-color-6 font-13 flex-item">编辑分享文案</span>
        <button size="mini" class="mini-btn font-12" @click="$pt.setClipboardData({data: textValue})">复制</button>
      </div>
      <div class="textarea-wrap">
        <textarea placeholder="编辑复制分享文案" :value="textValue" @input="textareaInput" placeholder-style="color:#666;" />
      </div>
      <p>本产品仅提供技术支持，请自行确保分享内容真实合法。</p>
    </div>
    <div class="height-90"></div>
    <div class="footer-bar flex flex-center">
      <span class="font-w font-18" :style="{backgroundColor: globalStyle.color2, color: globalStyle.styleType === 10 ? globalStyle.color4 : '#fff'}" @click="downLoad('all')">一键下载全部</span>
    </div>
  </div>
</template>
<script>
import ToastLayer from '@/components/ToastLayer'
export default {
  components: { ToastLayer },
  data() {
    return {
      mainNone: true,
      mainImgs: [],
      downIndex: 0,
      selectMain: [],
      toastShow: false,
      toastType: '',
      toastContent: '',
      toastDesc: '',
      textValue: '',
      timer: null,
      goods: {},
      globalStyle: {}
    }
  },
  onLoad() {
    // 初始化data
    Object.assign(this.$data, this.$options.data())
  },
  onShow() {
    let getAppInfo = this.$pt.getStorageSync('appInfo')
    this.globalStyle = getAppInfo.style
    this.mainImgs = []
    this.selectMain = []
    this.goods = JSON.parse(decodeURIComponent(this.getCurrentPage().query.goods))
    this.goods.images.forEach(item => {
      this.mainImgs.push({
        src: item,
        checked: true
      })
    })
    this.selectMain = this.$utils.deepClone(this.mainImgs)
    this.textValue = this.goods.shareCopy || ''
  },
  methods: {
    checkClick(item, index) {
      item.checked = !item.checked
      // 详情图选择
      if (!this.mainImgs.length) return
      if (item.checked) {
        this.selectMain.push(item)
      } else {
        this.selectMain.forEach((itemArr, indexArr) => {
          if (itemArr.src === item.src) {
            this.selectMain.splice(indexArr, 1)
          }
        })
      }
    },
    downLoad(type) {
      let that = this
      if (type === 'all') {
        this.$pt.setClipboardData({data: this.textValue})
        this.selectMain = this.$utils.deepClone(this.mainImgs)
      }
      if (!that.selectMain.length) return that.$utils.showToast({ title: '请选择下载图片' })
      // 获取用户授权的权限
      this.$pt.getSetting({
        success: res => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            // 如果没有授权图片保存功能,则进行授权申请操作
            that.$pt.authorize({
              scope: 'scope.writePhotosAlbum',
              success: function(opres) {
                // 授权图片保存功能成功
                that.$utils.showToast({ title: '下载中请勿操作' })
                // 调用保存图片函数
                that.drawPage()
              },
              fail: function(res) {
                that.toastShow = true
                that.toastType = 'warm'
                that.toastContent = '下载失败，请重新发起'
              }
            })
          } else {
            // 已经授权过图片保存功能的则，直接调用保存图片函数
            that.drawPage()
          }
        },
        fail: function(res) {
          that.toastShow = true
          that.toastType = 'warm'
          that.toastContent = '下载失败，请重新发起'
        }
      })
    },
    drawPage() {
      let that = this
      let arrData = that.selectMain
      if (this.downIndex < arrData.length) {
        this.$pt.downloadFile({
          url: arrData[that.downIndex].src + '?imageView2/2/w/700',
          success: (img) => {
            // 将图片保存到相册
            that.$pt.saveImageToPhotosAlbum({
              filePath: img.tempFilePath,
              success: (res) => {
                that.downIndex++
                that.toastShow = true
                that.toastType = 'loading'
                that.toastContent = '下载中请勿操作'
                that.toastDesc = that.downIndex + '/' + arrData.length
                return that.drawPage()
              },
              fail: function(err) {
                that.toastShow = true
                that.toastType = 'warm'
                that.toastContent = '下载失败，请重新发起'
                if (err.errMsg.indexOf('cancel') !== -1) return wx.hideLoading()
                console.log(`第${that.downIndex + 1}张保存失败`)
                return that.drawPage()
              }
            })
          },
          fail: function(res) {
            that.toastShow = true
            that.toastType = 'warm'
            that.toastContent = '下载失败，请重新发起'
          }
        })
      } else {
        this.downIndex = 0
        wx.hideLoading()
        setTimeout(() => {
          this.toastShow = true
          this.toastType = 'success'
          this.toastContent = '下载成功'
          this.toastDesc = '请查看手机相册'
        }, 800)
      }
    },
    textareaInput(e) {
      clearTimeout(this.timer)
      this.timer = null
      this.timer = setTimeout(() => {
        this.textValue = e.mp.detail.value
      }, 1000)
    }
  }
}
</script>
<style lang="less" scoped>
.container {
  background: #ffffff;
  min-height: 100vh;
  border-top: #e7e7e7 1px solid;
  .img-main {
    p {
      font-size: 11px;
      color: #999999;
      padding-left: 10px;
      padding-top: 2px;
    }
  }
  .img-title {
    .mini-btn {
      background-color: #fff;
      border: #333 1px solid;
      border-radius: 3px;
      color: #333;
      padding: 0;
      line-height: 18px;
      width: 39px;
      height: 20px;
    }
    margin-bottom: 10px;
  }
  .img-box {
    background: #f7f5f6;
    border-radius: 8px;
    padding: 12px 6px 0 6px;
    .img-bar {
      display: inline-block;
      vertical-align: top;
      width: 33.3%;
      text-align: center;
      margin-bottom: 12px;
    }
    &:after {
      content: '';
      display: block;
      clear: both;
    }
    /deep/ ._van-checkbox {
      justify-content: center;
      align-items: center;
      display: -webkit-box;
      display: -webkit-flex;
      display: flex;
    }
    /deep/ .van-checkbox {
      position: relative;
      .van-checkbox__icon-wrap {
        position: absolute;
        right: 6px;
        top: 6px;
      }
      .van-checkbox__icon {
        border-color: #d5d5d5;
        background-color: #ffffff;
      }
      .van-checkbox__label {
        margin-left: 0;
      }
    }
  }
  .footer-bar {
    position: fixed;
    left: 0;
    bottom: 0;
    background: #fff;
    width: 100%;
    height: 80px;
    text-align: center;
    span {
      display: inline-block;
      border-radius: 22.5px;
      color: #333333;
      height: 45px;
      line-height: 45px;
      width: 240px;
      background-color: #ffe100;
    }
  }
  .copywriting {
    .textarea-wrap {
      padding: 15px 12px;
      border-radius: 8px;
      background-color: #f5f5f5;
      textarea {
        color: #666;
      }
    }
    p {
      font-size: 11px;
      color: #999999;
      text-align: center;
      padding-top: 2px;
    }
  }
}
</style>
